
import pymongo
import time
from pymongo.errors import AutoReconnect


def from_to(from_ip, from_port, from_rs, to_ip, to_port, to_rs):
    from_tab = pymongo.MongoReplicaSetClient(
        from_ip +
        ":" +
        from_port,
        replicaSet=from_rs).local.oplog.rs
    to_tab = pymongo.MongoReplicaSetClient(
        to_ip + ":" + to_port,
        replicaSet=to_rs).todb.totab
    if to_tab.count() == 0:
        to_tab.insert(from_tab.find_one(sort=[("$natural", -1)]))
    last_time = to_tab.find_one(sort=[('ts', -1)])['ts']
    query = {'ts': {'$gt': last_time}}
    opts = {'tailable': True, 'await_data': True}
    cursor = from_tab.find(query, **opts)
    while cursor.alive:
        try:
            oplog = cursor.next()
            to_tab.insert(oplog)
        except (AutoReconnect, StopIteration) as e:
            print(e)
            print('sleep 0.1 seconds')
            time.sleep(0.1)
    return to_tab.count()

to_tab_counts = from_to(
    '192.168.0.101',
    '27017',
    'rs01',
    '192.168.0.101',
    '27019',
    'rs02')
print(to_tab_counts)